<style scoped lang="less">
	.demonstration {
		margin-right: 15px;
		margin-left: 15px;
	}

	.vipmassge {
		margin-right: 15px;
	}

	.el-button {
		margin-left: 15px;
	}

	.el-input__wrapper {
		margin-right: 15px;
	}


	#items1,
	#items2 {
		// margin-top: 30px;
		margin-left: 0px;
		display: flex;
		/* text-align: center; */
	}

	.el-table {
		width: 100vh;
		:deep(.cell){
			display: flex;
			align-items: center;
		}
	}

	.common-layout {
		background: #f2f3f5;

		.el-header {
			padding: 0 !important;
			height: 10vh;
		}

		.el-main {
			height: 86vh;
			width: 98%;
			background: #fff;
			// margin: 10px auto;
		}
	}

	.top {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20px;
	}

	.mya {
		display: inline-block;
		color: #4b5db9;
		width: 50px;
		text-align: center;
		cursor: pointer;
	}
</style>
<template>
	<div class="common-layout">
		<el-container>
			<el-header>
				<Header></Header>
			</el-header>
			<el-main>
				<div v-if="flag">
					<div class="top">
						<h3>
							会员列表
						</h3>
						<el-button plain type="primary" v-if="counter.btnsObj.addFlag" @click="add">{{counter.btnsObj.addName}}</el-button>
					</div>

					<!-- 添加会员对话框 -->
					<el-dialog v-model="dialogFormVisible" title="添加会员" width="500">
						<el-form :model="form"
							ref="ruleFormRef"
							:rules="rules"
						>
							<el-form-item label="会员编号:" prop="userAccount" :label-width="formLabelWidth">
								<el-input v-model="form.userAccount" style="width: 240px;" />
							</el-form-item>
							<el-form-item label="手机号:" prop="userTel" :label-width="formLabelWidth">
								<el-input v-model="form.userTel" style="width: 240px;" />
							</el-form-item>
							<el-form-item label="会员昵称:" prop="userName" :label-width="formLabelWidth">
								<el-input v-model="form.userName" style="width: 240px;" />
							</el-form-item>
							<el-form-item label="密码:" prop="userPassword" :label-width="formLabelWidth">
								<el-input type="password" v-model.trim="form.userPassword" style="width: 240px;" />
							</el-form-item>
							<el-form-item label="确认密码:" prop="surePassword" :label-width="formLabelWidth">
								<el-input type="password" v-model.trim="form.surePassword" style="width: 240px;" />
							</el-form-item>
							<el-form-item>
								<!-- <template #footer> -->
									<div class="dialog-footer">
										<el-button @click="dialogFormVisible = false">取消</el-button>
										<el-button type="primary" @click="save(ruleFormRef)">
											确定
										</el-button>
									</div>
								<!-- </template> -->
							</el-form-item>
							
						</el-form>
						
					</el-dialog>
					<!-- 点击标签显示框 -->
					<el-dialog v-model="dialogFormVisible1" title="标签" width="500">
						<el-form :model="formtwo">
							<el-form-item label="会员标签" label-width="100">
								<el-select v-model="formtwo.userTagId" placeholder="请选择会员标签" style="width: 270px;">
									<el-option v-for="item in tags" :key="item.userTagId" :label="item.userTagName"
										:value="item.userTagId" />
								</el-select>
							</el-form-item>
						</el-form>
						<template #footer>
							<div class="dialog-footer">
								<el-button @click="dialogFormVisible1 = false">取消</el-button>
								<el-button type="primary" @click="sure">
									确定
								</el-button>
							</div>
						</template>
					</el-dialog>
					<!-- 搜索栏 -->
					<div class="flex gap-4 mb-4 items-center" id="items1">
						<el-form-item label="会员信息">
							<el-input clearable v-model="inpusername" style="width: 210px;"
								placeholder="请输入会员编号/昵称/手机号" @change="searchData.userName=inpusername"/>
								
						</el-form-item>

						<el-form-item label="注册来源" label-width="90">
							<el-select style="width: 210px" v-model="searchData.orderSourceId" clearable placeholder="全部">
								<el-option v-for="item in source" :key="item.orderSourceId"
									:label="item.orderSourceName" :value="item.orderSourceId" />
							</el-select>
						</el-form-item>
					</div>
					<div class="flex gap-4 mb-4 items-center" id="items2">
						<el-form-item label=" 会员标签" >
							<el-select style="width: 210px" v-model="searchData.userTagId" clearable placeholder="全部" >
								<el-option v-for="item in tags" :key="item.userTagId" :label="item.userTagName"
									:value="item.userTagId"  />
							</el-select>
						</el-form-item>

						<el-form-item label="注册时间" label-width="90">
							<div class="block">
								<el-date-picker style="width:300px" v-model="timevalue" type="datetimerange"
									:shortcuts="shortcuts" range-separator="To" start-placeholder="开始时间"
									end-placeholder="结束时间" />
							</div>
						</el-form-item>
						<el-button type="primary" @click="search">搜索</el-button>
						<el-button plain @click="reset">重置</el-button>
					</div>
					<!-- 表格 -->
					<el-table :data="tableData" style="width: 100%" height="55vh">
						<el-table-column prop="userAccount" label="会员编号" width="80" />
						<el-table-column label="会员信息" width="120">
							<template #default="infor">
								<img src="../../public/头像.png" style="width:40px;height: 40px;object-fit: cover; ">
								<span>{{infor.row.userName}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="userTel" label="手机号" />
						<el-table-column prop="userScore" label="积分" />
						<el-table-column prop="userCanuseMoney" label="余额" />
						<el-table-column prop="userTagId" label="标签" />
						<el-table-column prop="orderSourceId" label="注册来源" />
						<el-table-column prop="userStatus" label="状态" />
						<el-table-column prop="createTime" label="注册时间"/>
						<el-table-column prop="userLastTime" label="最后访问时间"/>
						<el-table-column label="操作" width="150">
							<template #default="opt">
								<span class="mya" @click="detal(opt.row)">详情</span>
								<span class="mya" @click="showTag(opt.row)">标签</span>
							</template>
						</el-table-column>
					</el-table>

					<el-pagination layout="prev,pager,next" :page-count="total" :page-size="pageSize"
						v-model:current-page="pageIndex" @current-change="changePage"></el-pagination>
				</div>

				<VipDetails v-else @update-message="handleMessageUpdate"></VipDetails>
			</el-main>
		</el-container>
	</div>
</template>
<script setup>
	import {
		useRouter,
		useRoute
	} from 'vue-router';
	import {
		useCounterStore
	} from "../stores/counter"
	let route = useRoute();
	let router = useRouter();
	let counter = useCounterStore();

	counter.btns = route.meta.btns
	// console.log()
	import Header from '@/components/Header.vue'
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		Search,
		Lock,
		Calendar
	} from '@element-plus/icons-vue'
	import {
		VipList,
		UpdateVipTags,
		AddVip,
		MembershipSource,
		MembershipTags
	} from "@/api"
	import VipDetails from '@/components/VipDetails.vue';
	import { ElMessage } from 'element-plus'
	let pageIndex = ref(1);
	let pageSize = 5;
	let total = ref(0)
	let tableData = ref([])

	//获取会员列表
	const getList = async () => {
		let res = await VipList({
			pageIndex: pageIndex.value,
			pageSize: pageSize,
			siteId: Number(sessionStorage.getItem("siteId")),

		})
		// console.log("会员列表",res)
		tableData.value = res.userList
		for(var i=0;i<tableData.value.length;i++){
			if(tableData.value[i].userScore != null){
				tableData.value[i].userScore=Math.floor(tableData.value[i].userScore)
			}
		}
		total.value = res.pageCount
	}

	//按标签名或来源或电话搜索
	const formateDate = (data) => {
		let time = new Date(data)
		let year = time.getFullYear()
		let month = time.getMonth() + 1
		month = month < 10 ? "0" + month : month
		let day = time.getDate()
		day = day < 10 ? "0" + day : day
		let hour = time.getHours()
		hour = hour < 10 ? "0" + hour : hour
		let minute = time.getMinutes()
		minute = minute < 10 ? "0" + minute : minute
		let second = time.getSeconds()
		second = second < 10 ? "0" + second : second
		return `${year}-${month}-${day} ${hour}:${minute}:${second}`
	}
	let tagvalue = ref('')
	let sourcevalue = ref('')
	let inpusername = ref('')
	let timevalue = ref('')
	let searchData = reactive({
		pageIndex: pageIndex,
		pageSize: pageSize,
		siteId: Number(sessionStorage.getItem("siteId")),
		orderSourceId: sourcevalue.value,
		userTagId: tagvalue.value,
		userName: inpusername.value,
		createTimeStart: "",
		createTimeEnd: '',
	})
	const search = async () => {
		// console.log("searchData",searchData)
		if(timevalue.value){
			// console.log(timevalue.value)
			let startdata = timevalue.value[0].toLocaleString().split(" ")[0].replace(/\//g, '-')
			let startdataTime = timevalue.value[0].toLocaleString().split(" ")[1].replace(/:/g, '-')
			let startTime = startdata + " " + startdataTime
			let enddata = timevalue.value[1].toLocaleString().split(" ")[0].replace(/\//g, '-')
			let enddataTime = timevalue.value[1].toLocaleString().split(" ")[1].replace(/:/g, '-')
			let endtTime = enddata + " " + enddataTime
			searchData.createTimeStart = startTime
			searchData.createTimeEnd = endtTime
		}
		let data = {}
		for( let key in (searchData)){
			if(searchData[key]){
				// console.log(searchData[key])
				data[key] = searchData[key]
			}
		}
		let res=await VipList(data)
		 // console.log("data",data);
		tableData.value=res.userList
		for(var i=0;i<tableData.value.length;i++){
			if(tableData.value[i].userScore != null){
				tableData.value[i].userScore=Math.floor(tableData.value[i].userScore)
			}
		}
		total.value=res.pageCount
	}
	//重置
	const reset = () => {
		tagvalue.value=""
		sourcevalue.value=""
		inpusername.value=""
		sourcevalue.value=""
		getList()
		
		// info.value = ""
	}

	//获取会员标签下拉框
	const tags = ref([])
	const VipTaglist = async () => {
		let rop = await MembershipTags({
			siteId: Number(sessionStorage.getItem("siteId")),
		})
		// console.log("res",rop)
		tags.value = rop
	}

	//获取注册来源下拉框
	const source = ref([])
	const VipSourcelist = async () => {
		let rop = await MembershipSource()
		// console.log("res",rop)
		source.value = rop
	}

	//点击标签
	let formtwo = reactive({
		userTagId: ""
	})
	const dialogFormVisible1 = ref(false)
	const showTag = (row) => {
		dialogFormVisible1.value = true;
		formtwo.userTagId = row.userTagId
		sessionStorage.setItem("userId", row.userId)
	}
	//点击会员标签中的确定修改会员标签
	const sure = async () => {
		let response = await UpdateVipTags({
			siteId: Number(sessionStorage.getItem("siteId")),
			userId: Number(sessionStorage.getItem("userId")),
			userTagId: formtwo.userTagId
		})
		dialogFormVisible1.value = false;
		// console.log(formtwo.userTagId)
		// console.log(response);
		ElMessage.success(response)
		getList()
	}

	//点击添加会员
	// 表单校验
	const ruleFormRef=ref(null);
	const validatePass = (rule, value, callback) => {
		if (value === '') {
			callback(new Error('请输入密码'));
		} else {
			if (form.surePassword !== '') {
				ruleFormRef.value.validateField('surePassword');
			}
			callback();
		}
	};
	const validatePass2 = (rule, value, callback) => {
		if (value === '') {
			callback(new Error('请再次输入密码'));
		} else if (value !== form.userPassword) {
			callback(new Error('两次输入密码不一致!'));
		} else {
			callback();
		}
	}
	
	const rules = reactive({
		userAccount:[
			{ required: true, message: '请输入会员账号', trigger: 'blur' },
		],
		userTel:[
			{ required: true, message: '请输入电话', trigger: 'blur' },
			{ pattern:/^1([3-9])\d{9}$/, message: '请输入正确手机号', trigger: 'blur' },
		],
		userName:[
			{ required: true, message: '请输入会员账号', trigger: 'blur' },
		],
		userPassword:[
			{ required: true, message: '请输入密码', trigger: 'blur' },
			{ validator: validatePass, trigger: 'blur' }
		],
		surePassword:[
			{ required: true, message: '请再次输入密码', trigger: 'blur' },
			{ validator: validatePass2, trigger: 'blur' }
		],
	})
	const dialogFormVisible = ref(false)
	const formLabelWidth = '140px'
	let form = reactive({
		userAccount: "",
		userTel: "",
		userName: "",
		userPassword: "",
		surePassword: "",
		// siteId:Number(sessionStorage.getItem("siteId"))
	})
	const add = () => {
		dialogFormVisible.value = true
		form = reactive({
			userAccount: "",
			userTel: "",
			userName: "",
			userPassword: "",
			surePassword: "",
		})
	}
	//点击添加会员中的确定
	const save = (ruleForm) => {
		ruleForm.validate(async(valid) => {
		    if (valid) {
				// 表单验证成功
				let result = await AddVip({
					siteId: Number(sessionStorage.getItem("siteId")),
					"userAccount": form.userAccount,
					"userTel": form.userTel,
					"userName": form.userName,
					"userPassword": form.userPassword
				})
				// console.log("result", result)
				if(result != undefined){
					ElMessage.success(result)
				}
				dialogFormVisible.value = false
		    } else {
				// 验证不通过
				ElMessage.error('输入信息不正确');
				return false;
		    }
		});
	}

	//点击详情
	let flag = ref(true)
	const detal = (r) => {
		flag.value = false
		sessionStorage.setItem("userId", r.userId)
	}

	function handleMessageUpdate(newflag) {
		flag.value = newflag;
		// console.log(flag.value);
	}
	//点击分页器
	const changePage = (page) => {
		// console.log(page)
		pageIndex.value = page;
		search()
	}
	
	




	const value2 = ref('')

	const shortcuts = [{
			text: 'Last week',
			value: () => {
				const end = new Date()
				const start = new Date()
				start.setDate(start.getDate() - 7)
				return [start, end]
			},
		},
		{
			text: 'Last month',
			value: () => {
				const end = new Date()
				const start = new Date()
				start.setMonth(start.getMonth() - 1)
				return [start, end]
			},
		},
		{
			text: 'Last 3 months',
			value: () => {
				const end = new Date()
				const start = new Date()
				start.setMonth(start.getMonth() - 3)
				return [start, end]
			},
		},
	]

	onMounted(() => {
		getList()
		VipTaglist()
		VipSourcelist()
	})
</script>